//http://fitpro.sourceforge.net/eclipse_install.html
package com.fit;

import java.io.IOException;
import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.SQLException;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.Date;

import com.source.Sale;
import com.source.SaleDAO;
import com.source.SerializationUtil;

public class InitiateSaleOperation extends fit.ColumnFixture {

	public String name;
	public String start;
	public String end;
	public int rating;
	public int countClients;
	public int ageSegmentStart;
	public int ageSegmentEnd;
	public String residentialArea;
	public int productId;


	public boolean initiateSaleOperation() {	
		Sale initiatedSale;

		SaleDAO saleDAO = new SaleDAO(this.getConnection());

		initiatedSale = new Sale();
		initiatedSale.setId(saleDAO.selectMaxId()+1);


		if(name==null || "".equals(name)){
			return false;
		}else{
			initiatedSale.setName(name);
		}

		SimpleDateFormat format = new SimpleDateFormat("yyyy-MM-dd");
		Date dateStart = null;
		Date dateEnd = null;
		try {
			dateStart = format.parse(start);
			dateEnd = format.parse(end);
		} catch (ParseException e1) {
			e1.printStackTrace();
		}

		if (dateStart.compareTo(dateEnd) <= 0) {
			initiatedSale.setStart(start);
			initiatedSale.setEnd(end);
		}else{
			return false;
		}

		initiatedSale.setCountClients(countClients);
		if(ageSegmentStart>=0 && ageSegmentEnd <=120){
			initiatedSale.setAgeSegmentStart(ageSegmentStart);
			initiatedSale.setAgeSegmentEnd(ageSegmentEnd);
		}else{
			return false;
		}

		if("".equals(residentialArea)){
			return false;
		}else if(!residentialArea.equalsIgnoreCase("North") && !residentialArea.equalsIgnoreCase("Center") && 
				!residentialArea.equalsIgnoreCase("South") && !residentialArea.equalsIgnoreCase("Sharon") && 
				!residentialArea.equalsIgnoreCase("Jerusalem")){
			return false;
		}else{
			initiatedSale.setResidentialArea(residentialArea);
		}


		initiatedSale.setProductId(productId);

		try {
			SerializationUtil.serialize(initiatedSale, "c:\\sale.out");
		} catch (IOException e) {
			e.printStackTrace();
		}

		saleDAO.insert();
		return true;
	}

	public Connection getConnection(){
		String url = "jdbc:mysql://"+ "localhost" +"/" + "EmployeePortalDb";
		Connection conn = null;
		try {
			Class.forName("com.mysql.jdbc.Driver");
			conn = DriverManager.getConnection(url, "root", "Braude");
		} catch (ClassNotFoundException e) {
			e.printStackTrace();
		} catch (SQLException e) {
			e.printStackTrace();
		}

		return conn;
	}
}
